
const ciManagementController = function(HttpService) {
  'ngInject';

  const vm = this;

  vm.ciItems = [];
  vm.isLoading = false;
  vm.showCreateForm = false;
  vm.currentCiItem = null;

  vm.filters = {
    ci_type: '',
    environment: '',
    business_importance: '',
    status: 'active',
    owner_department: '',
    search: ''
  };

  vm.newCiItem = {
    ci_code: '',
    ci_name: '',
    ci_type: 'server',
    category: '',
    location: '',
    ip_address: '',
    hostname: '',
    environment: 'production',
    vendor: '',
    model: '',
    owner_department: '',
    business_importance: 'medium',
    description: '',
    status: 'active'
  };

  // CI类型选项
  vm.ciTypes = [
    { value: 'server', label: '服务器' },
    { value: 'application', label: '应用系统' },
    { value: 'database', label: '数据库' },
    { value: 'network', label: '网络设备' },
    { value: 'storage', label: '存储设备' },
    { value: 'security', label: '安全设备' },
    { value: 'other', label: '其他' }
  ];

  // 环境类型选项
  vm.environments = [
    { value: 'production', label: '生产环境' },
    { value: 'staging', label: '预生产环境' },
    { value: 'testing', label: '测试环境' },
    { value: 'development', label: '开发环境' }
  ];

  // 业务重要性选项
  vm.businessImportanceOptions = [
    { value: 'critical', label: '关键' },
    { value: 'high', label: '高' },
    { value: 'medium', label: '中' },
    { value: 'low', label: '低' }
  ];

  // 状态选项
  vm.statusOptions = [
    { value: 'active', label: '正常' },
    { value: 'inactive', label: '停用' },
    { value: 'maintenance', label: '维护中' },
    { value: 'retired', label: '已退役' }
  ];

  // 部门列表
  vm.departments = [];

  // 初始化
  vm.$onInit = function() {
    loadCiItems();
    loadDepartments();
  };

  function loadCiItems() {
    vm.isLoading = true;
    
    const params = {};
    if (vm.filters.ci_type) params.ci_type = vm.filters.ci_type;
    if (vm.filters.environment) params.environment = vm.filters.environment;
    if (vm.filters.business_importance) params.business_importance = vm.filters.business_importance;
    if (vm.filters.status) params.status = vm.filters.status;
    if (vm.filters.owner_department) params.owner_department = vm.filters.owner_department;
    if (vm.filters.search) params.search = vm.filters.search;

    HttpService.ciItems.list(params)
      .then(response => {
        if (response.success) {
          vm.ciItems = response.data;
        } else {
          console.error('加载CI项目列表失败:', response.message);
          alert('加载CI项目列表失败：' + response.message);
        }
      })
      .catch(error => {
        console.error('加载CI项目列表失败:', error);
        alert('加载CI项目列表失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isLoading = false;
      });
  }

  function loadDepartments() {
    HttpService.departments.list({ status: 1 })
      .then(response => {
        if (response.success) {
          vm.departments = response.data.map(dept => dept.name);
        }
      })
      .catch(error => {
        console.error('加载部门列表失败:', error);
      });
  }

  vm.searchCiItems = function() {
    loadCiItems();
  };

  vm.clearFilters = function() {
    vm.filters = {
      ci_type: '',
      environment: '',
      business_importance: '',
      status: 'active',
      owner_department: '',
      search: ''
    };
    loadCiItems();
  };

  vm.showCreateCiItemForm = function() {
    vm.showCreateForm = true;
    vm.newCiItem = {
      ci_code: '',
      ci_name: '',
      ci_type: 'server',
      category: '',
      location: '',
      ip_address: '',
      hostname: '',
      environment: 'production',
      vendor: '',
      model: '',
      owner_department: '',
      business_importance: 'medium',
      description: '',
      status: 'active'
    };
  };

  vm.hideCreateForm = function() {
    vm.showCreateForm = false;
    if (vm.ciItemForm) {
      vm.ciItemForm.$setPristine();
      vm.ciItemForm.$setUntouched();
    }
  };

  vm.createCiItem = function() {
    if (vm.ciItemForm.$invalid) {
      alert('请填写必填字段');
      return;
    }

    vm.isLoading = true;

    HttpService.ciItems.create(vm.newCiItem)
      .then(response => {
        if (response.success) {
          alert('CI项目创建成功！');
          vm.hideCreateForm();
          loadCiItems();
        } else {
          alert('CI项目创建失败：' + response.message);
        }
      })
      .catch(error => {
        alert('CI项目创建失败：' + (error.message || '网络错误'));
      })
      .finally(() => {
        vm.isLoading = false;
      });
  };

  // 获取CI类型标签
  vm.getCiTypeLabel = function(ciType) {
    const type = vm.ciTypes.find(t => t.value === ciType);
    return type ? type.label : ciType;
  };

  // 获取环境标签
  vm.getEnvironmentLabel = function(environment) {
    const env = vm.environments.find(e => e.value === environment);
    return env ? env.label : environment;
  };

  // 获取业务重要性标签
  vm.getBusinessImportanceLabel = function(importance) {
    const imp = vm.businessImportanceOptions.find(i => i.value === importance);
    return imp ? imp.label : importance;
  };

  // 获取状态标签
  vm.getStatusLabel = function(status) {
    const stat = vm.statusOptions.find(s => s.value === status);
    return stat ? stat.label : status;
  };

  // 获取业务重要性徽章样式
  vm.getBusinessImportanceBadgeClass = function(importance) {
    const classMap = {
      'critical': 'badge-danger',
      'high': 'badge-warning',
      'medium': 'badge-info',
      'low': 'badge-secondary'
    };
    return classMap[importance] || 'badge-secondary';
  };

  // 获取状态徽章样式
  vm.getStatusBadgeClass = function(status) {
    const classMap = {
      'active': 'badge-success',
      'inactive': 'badge-secondary',
      'maintenance': 'badge-warning',
      'retired': 'badge-danger'
    };
    return classMap[status] || 'badge-secondary';
  };
};

const ciManagementComponent = {
  templateUrl: 'src/app/pages/ci-management/ci-management.template.html',
  controller: ciManagementController
};

function initCiManagementController() {
  const angular = window.angular;
  
  if (!angular) {
    console.error('Angular 未找到，无法初始化CI管理控制器模块');
    return;
  }

  angular.module('app.pages.ciManagement', [])
    .component('ciManagementPage', ciManagementComponent);
}

// Listen for vendor libs loaded event
window.addEventListener('vendorLibsLoaded', () => {
  initCiManagementController();
});

// If Angular already loaded, init directly  
if (window.angular) {
  initCiManagementController();
}